<!-- 用于显示每个测试项（一个数据集）的情况 -->

<template>
    <a-spin :spinning="loading" :delay="1">
        <a-card :bordered="false" size="small">
            <a-row justify="space-around">
                <!-- <a-col :span="3" v-for="db in items" :key="db in items">
                    <test-info :test="row" :dataset="col" :database="db"></test-info>
                </a-col> -->
            </a-row>
            <a-row justify="space-around">
                <a-col :span="24">
                    <!-- <div :id="divid" style="width: 100%; height: 200px"></div> -->
                    <!-- <a-table :columns="columns" :data-source="benchmark" size="small" /> -->
                    <a-collapse>
                        <!-- <a-collapse-panel :header="abstract.title" :showArrow="true" :class="abstract.type"> -->
                            <!-- <a-button type="primary">Primary Button</a-button>
                            <a-button>Default Button</a-button>
                            <a-button type="dashed">Dashed Button</a-button>
                            <a-button type="text">Text Button</a-button>
                            <a-button type="link">Link Button</a-button> -->
                        <!-- </a-collapse-panel> -->
                        <a-collapse-panel v-for="t in hisGrpTest" :key="t.id" :class="t.type" :showArrow="false">
                            <template v-slot:header>
                                <div style="width:100%; display:flex;justify-content: space-between;">
                                    <text>{{t.title}}</text>
                                    <template v-if="t.kv.length>0">
                                        <a-tooltip v-for="kv in t.kv" :key="kv[0]">
                                            <template #title>{{kv[0]}}</template>
                                            <a-tag>{{kv[1]}}</a-tag>
                                        </a-tooltip>
                                    </template>
                                    <text class="time-string">
                                        <text v-if="t.cnt>1">(x{{t.cnt}}) </text>
                                        {{t.time}}
                                    </text>
                                </div>
                                
                            </template>
                            <!-- <a-popover>color="pink" -->
                                <!-- <template #content>{{JSON.stringify(t.content)}}</template> -->
                                <a-button @click="runit(t)">启动测试</a-button>
                                <a-list size="small" v-if="t.content && t.content.length>0">
                                    <a-list-item v-for="tt in t.content" :key="tt.createdAt">
                                        <div style="width:100%; display:flex;justify-content: space-between;">
                                            {{tt.title}} 
                                            <template v-if="tt.kv.length>0">
                                                <a-tooltip v-for="kv in tt.kv" :key="kv[0]">
                                                    <template #title>{{kv[0]}}</template>
                                                    <a-tag>{{kv[1]}}</a-tag>
                                                </a-tooltip>
                                            </template>
                                            <text style="color:lightgray">{{t.time}}</text>
                                        </div>
                                    </a-list-item>
                                </a-list>
                                <div v-else>{{JSON.stringify(t.content)}}</div>
                            <!-- </a-popover> -->
                        </a-collapse-panel>
                        
                    </a-collapse>
                    <!-- <a-list size="small">
                        <a-list-item v-for="t in history" :key="t.createdAt" >
                            <a-tooltip>
                                <template #title>{{t.timeStr}} ({{t.durStr}})</template>
                                {{t.title}}
                            </a-tooltip>
                        </a-list-item>
                    </a-list> -->
                </a-col>
            </a-row>
        </a-card>
        <a-modal v-model:visible="showModal" title="开启测试" @ok="submit">
            <a-form
                :model="currentValue"
                name="basic"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16 }"
                autocomplete="off"
                @finish="onFinish"
                @finishFailed="onFinishFailed"
                >
                <a-form-item v-for="item in currentValue" v-bind:key="item.key"
                    :label="item.key.toUpperCase()"
                    :name="item.key"
                    >
                    <a-input v-model:value="item.val" placeholder="" />
                </a-form-item>
                <!-- <a-form-item :wrapper-col="{ offset: 8, span: 16 }"> :value="item.val"
                    <a-button type="primary" html-type="submit">Submit</a-button>
                </a-form-item> -->
            </a-form>
        </a-modal>
    </a-spin>
</template>

<script>
    /* eslint-disable */
    import TestInfo from './TestInfo.vue'
    import moment from 'moment'
    import 'moment/locale/zh-cn'
    import * as echarts from "echarts";
    const ECHART_OPTS = {

    }
    function totalSpace(){
        
    }
    function obj2arr(obj){
        var copy = []
        for (var attr in obj) {
            copy.push({key:attr, val:obj[attr]})
        }
        return copy
    }
    function arr2obj(arr){
        var copy = {}
        for(let item of arr){
            copy[item.key]=item.val
        }
        return copy
    }
    function cloneObj(obj){
        var copy = {}
        for (var attr in obj) {
            copy[attr]=obj[attr]
        }
        return copy
    }
    export default {
        name: 'TestHistory',
        props: {
            row: String,
            col: String,
            items: Array,
        },
        components: {
            TestInfo,
        },
        data() {
            return {
                loading: true,
                abstract:{
                    type: 'running',
                    title: '测试中'
                },
                showModal: false,
                currentJob: 'build',
                currentValue:[],
            }
        },
        created() {
            // console.log(this.row, this.col, this.items)
        },
        mounted() {
            setTimeout(() => {
                this.loading = false
            }, 2000)
            // var myChart = echarts.init(document.getElementById(this.divid));
            //          var series = this.scatterReqCntDuration
            //          console.log(this.row, this.col)
            // // 指定图表的配置项和数据
            // var option = {
            // 	animation: false,
            // 	title: {
            // 		// text: 'ECharts 入门示例'
            // 	},
            // 	tooltip: {},
            // 	legend: {
            // 		// data: ['销量']
            // 	},
            // 	xAxis: {
            // 		type: 'value',
            // 		// data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
            // 	},
            // 	yAxis: {
            // 		type: 'value',
            // 	},
            // 	series
            // };
            // myChart.setOption(option);
        },
        methods: {
            runit(t) {
                console.log(t)
                const tests = this.testParams
                let name = t.id=='space'?'build':'test'
                this.currentJob = name
                console.log(tests, name, tests[name])
                this.currentValue = tests[name]
                this.showModal = true
            },
            submit(e){
                console.log(this.currentValue)
                this.showModal = false
                let args = arr2obj(this.currentValue)
                this.$store.dispatch('buildJenkins', this.currentJob, args)
            },
            onFinish(value){
                console.log(this.currentValue)
                let name = ''
                // 
            },
            onFinishFailed(e){
                console.error(e)
            }
        },
        watch:{
            
            params(newVal, oldVal){
                let ret = {}
                for(let p of newVal){
                    ret[p.key] = p.val
                }
                this.currentValue = ret
            }
        },
        computed: {
            divid() {
                return 'echart-' + this.row + '-' + this.col
            },
            history() {
                const res = this.$store.getters.grpResDataDbSize
                let key = (this.col+':'+this.row).toLowerCase()
                // console.log(key)
                let tmp = []
                if(res[key]) tmp = res[key]
                // console.log(tmp)
                tmp.sort((a, b) => {
                    return b.createdAt.getTime() - a.createdAt.getTime()
                })
                let his = []
                // console.log(this.row + '-' + this.col, tmp.map(i=>moment(i.createdAt).format('M/D H:m')))
                let concnt = 0
                let childs = []
                for (let j in tmp) {
                    let i = tmp[j]
                    i.timeStr = moment(i.createdAt).format('M/D H:m')
                    i.time = moment(i.createdAt).fromNow()
                    i.durStr = moment.duration(i.content.duration, "seconds").humanize();
                    let index = ['space', 'oltp', 'append', 'update'].indexOf(i.test)
                    i.title = i.test + (i.test=='space'?'': i.content.reqcnt + '-') + ' (' + i.durStr + ') ' + i.time

                    if (index >= 0) {
                        if (childs.length > 0) {
                            his.push({
                                title: childs.length + '个读测试',
                                children: childs
                            })
                            childs = []
                        }
                        his.push(i)
                        i.type = 'write'
                        if (index == 0) {
                            i.type = 'build'
                            i.title = i.test + ' (' + i.durStr + ') ' + i.time
                            // break;
                        }
                    } else {
                        childs.push(i)
                        i.type = 'read'
                    }
                    if(i.content.running) i.type='running'
                }
                return his
            },
            hisGrpTest() {
                const res = this.$store.getters.grpResDataDbSize
                let key = (this.col+':'+this.row).toLowerCase()
                // console.log(key)
                let tmp = []
                if(res[key]) tmp = res[key]
                // console.log(tmp)
                
                let history = {}
                // console.log(this.row + '-' + this.col, tmp.map(i=>moment(i.createdAt).format('M/D H:m')))
                let concnt = 0
                let running = {}
                for (let j in tmp) {
                    let i = tmp[j]
                    i.timeStr = moment(i.createdAt).format('M/D H:m')
                    i.time = moment(i.createdAt).fromNow()
                    i.durStr = moment.duration(i.content.duration, "seconds").humanize();
                    i.title = i.test
                    i.kv = []
                    if(i.test!='space') i.kv.push(['请求数', i.content.reqcnt])
                    i.kv.push(['持续时间',i.durStr])
                    if(i.jenkins===i.content) i.kv.push([i.jenkins.jenkins, 'J'])
                    if(!(i.test in history)) history[i.test] = []
                    history[i.test].push(i)
                    if(i.content.running) running[i.test] = true
                }
                let ret = []
                for(let t in history){
                    let lst = history[t]
                    lst.sort((a, b) => {
                        // if(a==undefined || b==undefined) console.log(t,a,b)
                        return b.createdAt.getTime() - a.createdAt.getTime()
                    })
                    let index = ['space', 'oltp', 'append', 'update'].indexOf(t)
                    ret.push({
                        id: t,
                        content: lst,
                        title: lst[0].title,
                        time: lst[0].time,
                        cnt: lst.length,
                        type: running[t]?'running':(index==0?'build':(index>0?'write':'read')),
                        kv: lst[0].kv
                    })
                }
                ret.sort((a,b)=>{
                    return b.content[0].createdAt.getTime() - a.content[0].createdAt.getTime()
                })
                return ret
            },
            testParams(){
                const jobs = this.$store.state.jenkins_jobs
                let myJobs = {}
                for(let name in jobs){
                    let j = cloneObj(jobs[name])
                    if(name=='build'){
                        let arr = this.row.split('.')
                        j.data_size = arr[1].toLowerCase()
                        j.db_name = arr[0].toUpperCase()
                        j.dataset = this.col
                        j.device = 'data'
                    }
                    myJobs[name]=obj2arr(j)
                }
                return myJobs
            },
            // scatterReqCntDuration(){
            //     let his = this.history
            //     let seriesData = {}
            //     for(let t of his){
            //         let y = t.content.duration
            //         let x = t.content.reqcnt
            //         let series = t.test
            //         if(!(series in seriesData)){
            //             seriesData[series] = []
            //         }
            //         seriesData[series].push([x,y, t.time])
            //     }
            //     let result = []
            //     for(let s in seriesData){
            //         result.push({
            //             type: 'scatter',
            //             data: seriesData[s],
            //             name: s
            //         })
            //     }
            //     return result
            // }
        }
    }
</script>

<style scoped>
    .build {
        background-color: #e1fae9;
    }
    .build > .time-string{
        color: darkgreen
    }
    .running {
        background-color: #09fa5a;
    }
    .running > .time-string{
        color:#000
    }
    .write {
        background-color: #ffbebe;
    }
    .write > .time-string{
        color:#ccc
    }
    .read {
        
    }
    .read > .time-string{
        color:lightgray
    }
    
    .ant-collapse-header {
        padding-top: 2px;
        padding-bottom: 2px;
    }
    .time-string{
        color:lightgray
    }
</style>
